package com.example.config;

import com.alibaba.fastjson.JSON;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.common.result.Result;
import com.example.entity.mqtt.Mqunit;
import com.example.entity.mqtt.MqunitHis;
import com.example.entity.mysql.Mqunits;
import com.example.mapper.MqunitMapper;
import com.example.mapper.MqunitsMapper;
import com.example.service.MqunitHisService;
import com.example.service.MqunitService;
import com.example.service.impl.SimpleMasterExample;
import com.example.untils.TimeUtils;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Description : MQTT接受服务的回调类
 * @Author : Sherlock
 * @Date : 2023/8/1 16:29
 */
@Component
public class MqttAcceptCallback implements MqttCallbackExtended {

    private static final Logger logger = LoggerFactory.getLogger(MqttAcceptCallback.class);

    @Autowired
    private MqttAcceptClient mqttAcceptClient;

    @Autowired
    private MqttProperties mqttProperties;

    @Resource
    private MqunitMapper mqunitMapper;

    @Resource
    private MqunitsMapper mqunitsMapper;

    @Resource
    private SimpleMasterExample simpleMasterExample;

    @Resource
    private MqunitService mqunitService;

    @Resource
    private MqunitHisService mqunitHisService;

    /**
     * 客户端断开后触发
     *
     * @param throwable
     */
    @Override
    public void connectionLost(Throwable throwable) {
//        logger.info("连接断开，可以重连");
        if (MqttAcceptClient.client == null || !MqttAcceptClient.client.isConnected()) {
//            logger.info("【emqx重新连接】....................................................");
            mqttAcceptClient.reconnection();
        }
    }

    /**
     * 客户端收到消息触发
     *
     * @param topic       主题
     * @param mqttMessage 消息
     */
    @Override
    @Transactional(rollbackFor = Exception.class) // 批量执行需要加上事务,其中报错,进行回滚操作
    @DS("mes")
    public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
//        logger.info("【接收消息主题】:" + topic);
//        logger.info("【接收消息Qos】:" + mqttMessage.getQos());
//        logger.info("【接收消息内容】:" + new String(mqttMessage.getPayload()));
        String s = new String(mqttMessage.getPayload(), "UTF-8");
//        logger.info("【查看json格式】:"+s);
        String result = s.replace("[", "").replace("]", "");
        Mqunit mqunit = JSON.parseObject(result, Mqunit.class);
        mqunit.setName(topic);
        mqunit.setCrateDateTime(TimeUtils.getFullNowTime());
        try{
//            Mqunits mqunits = new Mqunits();
//            BeanUtils.copyProperties(mqunit,mqunits);
//            //新增数采列表
//            this.mqunitsMapper.insert(mqunits);
            Mqunit mqunit1 = this.mqunitMapper.selectOne(new QueryWrapper<Mqunit>().eq("name", mqunit.getName()));
            if (mqunit1==null){
                int insert = this.mqunitMapper.insert(mqunit);
                if (insert>0){
                    Result.success("添加成功");
                }
            }else{
                if (mqunit.getCount()!=null){
                    mqunit1.setCount(mqunit.getCount());
                }
                if (mqunit.getLength()!=null){
                    mqunit1.setLength(mqunit.getLength());
                }
                if (mqunit.getStatus()!=null){
                    if (Integer.parseInt(mqunit.getStatus())==1){
                        if(mqunit1.getStatus().equals("关机")){
                            try {
                                if (mqunit1!=null){
                                    String string = this.simpleMasterExample.writeDemo2(mqunit1.getIp(), mqunit1.getPort(), mqunit1.getCunqi());
                                    if (string.equals("0x000000")){
                                        MqunitHis mqunitHis =new MqunitHis();
                                        mqunitHis.setMid(mqunit1.getId());
                                        mqunitHis.setName(mqunit1.getName());
                                        mqunitHis.setCount(mqunit1.getCount());
                                        mqunitHis.setLength(mqunit1.getLength());
                                        mqunitHis.setStatus(mqunit1.getStatus()+"-重启自动清零");
                                        mqunitHis.setReset(mqunit1.getReset());
                                        SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                        String format = dateFormat.format(new Date());
                                        mqunitHis.setTime(format);
                                        mqunit1.setLength(0.00);
                                        mqunit1.setCount(0);
                                        boolean b = this.mqunitService.updateById(mqunit1);
                                        Result insert = this.mqunitHisService.insert(mqunitHis);
                                        if (insert.getCode().equals("200")&&b){
                                            Result.success("重启自动清零成功下发");
                                        }
                                        Result.success("重启自动清零成功下发,插入历史表失败或修改数据失败");
                                    }
                                    Result.error("重启自动清零成功下发");
                                }
                                Result.error("该id不存在,重启自动清零下发失败");
                            } catch (Exception e) {
                                Result.error("重启自动清零下发异常报错信息"+e);
                            }
                        }
                        mqunit1.setStatus("加工");
                    }else {
                        mqunit1.setStatus("关机");
                    }
                }
                this.mqunitMapper.updateById(mqunit1);
            }
        }catch (Exception e){
            logger.error("发生错误"+e);
            throw new Exception();
        }
    }

    /**
     * 发布消息成功
     *
     * @param token token
     */
    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {
        String[] topics = token.getTopics();
        for (String topic : topics) {
            logger.info("向主题【" + topic + "】发送消息成功！");
        }
        try {
            MqttMessage message = token.getMessage();
            byte[] payload = message.getPayload();
            String s = new String(payload, "UTF-8");
            logger.info("【消息内容】:" + s);
        } catch (Exception e) {
            logger.error("MqttAcceptCallback deliveryComplete error,message:{}", e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 连接emq服务器后触发
     *
     * @param b
     * @param s
     */
    @Override
    public void connectComplete(boolean b, String s) {
        logger.info("============================= 客户端【" + MqttAcceptClient.client.getClientId() + "】连接成功！=============================");
        // 以/#结尾表示订阅所有以test开头的主题
        // 订阅所有机构主题
        mqttAcceptClient.subscribe(mqttProperties.getDefaultTopic(), 0);
    }
}
